var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bcrypt   = require('bcrypt-nodejs');
var LocalStrategy = require('passport-local');

// Mongoose Schema
var userSchema = mongoose.Schema({
    email       : String,
    password    : String
});
userSchema.methods.generateHash = function(password) {
   return bcrypt.hashSync(password, bcrypt.genSaltSync(4), null);
};
userSchema.methods.validPassword = function(password) {
   return bcrypt.compareSync(password, this.password);
};
var User = mongoose.model('user', userSchema);

// Passport
passport.serializeUser(function(user, done) { 
    done(null, user._id);
});
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});
passport.use('my-local-signup', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true 
},  function(req, email, password, done) {
    var regex = new RegExp(["^", email, "$"].join(""),"i");
    User.findOne({ 'email' :  regex }, function(err, user) {
        if (err) return done(err);
        if (user) {
            return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
        } else {
            var newUser      = new User();
            newUser.email    = email;
            newUser.password = newUser.generateHash(password);
            newUser.save(function(err) {
                if (err) throw err;
                return done(null, newUser);
            });
        }
    });
}));
passport.use('my-local-login', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true 
}, function(req, email, password, done) {
    var regex = new RegExp(["^", email, "$"].join(""),"i");
    User.findOne({ 'email' :  regex }, function(err, user) {
        if (err) return done(err);
        if (!user) return done(null, false, req.flash('loginMessage', 'No user found.'));
        if (!user.validPassword(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
        return done(null, user);
    });
}));




var app = express();
app.listen(80);
app.locals.pretty = true;
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(cookieParser());
app.use(session( {secret: 'my_super_secrete_word', resave: true, saveUninitialized: true } ));
//app.use(bodyParser());
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

mongoose.connect('mongodb://localhost:27017/testdb', function(err){
    if(err)  {
        console.log('cannot connect db');
        process.exit(1);
    }
});


app.get('/users/logout', function(req, res){
    req.logout();
    res.redirect('/');
});
app.get('/users/login', function(req, res) {
    res.render('login', { message: req.flash('loginMessage') });
});
app.post('/users/login', passport.authenticate('my-local-login', {
  successRedirect : '/', 
  failureRedirect : '/users/login',   
  failureFlash : true
}));

app.get('/users/signup', function(req, res) {
  res.render('signup', { message: req.flash('signupMessage') });
});
app.post('/users/signup', passport.authenticate('my-local-signup', {
  successRedirect : '/', 
  failureRedirect : '/users/signup', 
  failureFlash : true
}));
app.get('/', function(req, res, next){
    req.isAuthenticated();
    next();
},function(req, res) {
    res.render('index', {user: req.user});
});

